package com.csrcb.filter;

import com.csrcb.constants.MyConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @Classname TraceIdFilter
 * @Description TraceId使用的过滤器
 * @Date 2021/8/16 10:07
 * @Created by gangye
 */
//@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")   //过滤器过滤路径可以在注解中配置，也可在后面的配置类中在代码中增加
public class TraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(MyConstant.TRACE_ID_HTTP_FIELD);
        String parentSpanId = request.getHeader(MyConstant.PARENT_SPAN_ID_HTTP_FIELD);
        if (StringUtils.isNotBlank(parentSpanId)){
            MDC.put(MyConstant.PARENT_SPAN_ID_MDC_FIELD,parentSpanId);
        }
        String spanId = request.getHeader(MyConstant.SPAN_ID_HTTP_FIELD);
        if (StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString().replace("-","").substring(0,16);
            spanId = traceId;
        }
        if (StringUtils.isBlank(spanId)){
            spanId = UUID.randomUUID().toString().replace("-","").substring(0,16);
        }
        MDC.put(MyConstant.TRACE_ID_MDC_FIELD, traceId);//设置自定义的traceId
        MDC.put(MyConstant.TRACE_ID_HTTP_FIELD, traceId);//设置X-B3-TraceId
        MDC.put(MyConstant.SPAN_ID_MDC_FIELD, spanId);//设置自定义的spanId

        try {
            filterChain.doFilter(request,response);
        }finally {
            MDC.remove(MyConstant.TRACE_ID_MDC_FIELD);
            MDC.remove(MyConstant.TRACE_ID_HTTP_FIELD);
            MDC.remove(MyConstant.SPAN_ID_MDC_FIELD);
            MDC.remove(MyConstant.PARENT_SPAN_ID_MDC_FIELD);
        }

    }

}
